package GUILayer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import CtrLayer.CustomerCtr;
import ModelLayer.Customer;

public class CustomerGUI {
	private JPanel panel;
	private JTable customerTable;
	private Object[][] data; // data for tablefremove
	
	private int size; // number of rows in table
	private static int idC = 1000;
	private static CustomerCtr customerCtr = new CustomerCtr();

	public CustomerGUI() {

	}

	private JPanel makeGridListCustomers() {
		Iterator<?> it = customerCtr.getCustomersIterator();
		size = customerCtr.getCustomerSize();

		String[] columnNames = { "Id", "Name", "Address", "Postal Code", "Phone", "email", "Type", "CVR", "Delete" };
		data = new Object[size][columnNames.length];

		int i = 0;
		while (it.hasNext()) {
			Customer cust = (Customer) it.next();
			data[i][0] = cust.getId();
			data[i][1] = cust.getName();
			data[i][2] = cust.getAddress();
			data[i][3] = cust.getPostCode();
			data[i][4] = cust.getPhone();
			data[i][5] = cust.getEmail();
			data[i][6] = cust.getType();
			data[i][7] = cust.getCvr();
			data[i][8]= Boolean.FALSE;
			i++;
		}

		JPanel gridCustomer = new JPanel();
		DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int col) {
				return (col == 8);
			}

			public Class<?> getColumnClass(int col) {
				if (col == 8)
					return Boolean.class;
				return super.getColumnClass(col);
			}
		};

		customerTable = new JTable(dtm);
		customerTable.getTableHeader().addMouseListener(new MouseListener() {
			public void mouseClicked(MouseEvent e) {
				int col = customerTable.columnAtPoint(e.getPoint());
				if (col == 8) {
					if(Main.access==false)	
					{
						JOptionPane.showConfirmDialog(null, "You don't have access","Info",JOptionPane.CLOSED_OPTION);
						return;
					}
					int selected = getSelectedCustomer(customerTable);
					if (selected == 0) {
						JOptionPane.showConfirmDialog(null,
								"You didn't select any Customers", "Info",
								JOptionPane.CLOSED_OPTION);
					} else {
						int answer = JOptionPane.showConfirmDialog(null,
								"Are you sure you want to delete " + selected
										+ " customer(s) ?", "Confirm delete",
								JOptionPane.YES_NO_OPTION);
						if (answer == JOptionPane.YES_OPTION) {
							deleteSelectedCustomer(customerTable);
						}
					}
				}
			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub
				
			}

		});

		TableColumnModel tcm = customerTable.getColumnModel();
		tcm.getColumn(0).setPreferredWidth(40);
		
		JScrollPane customerTableScroll = new JScrollPane(customerTable);
		customerTableScroll.setPreferredSize(new Dimension(600, 145));
		customerTableScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		customerTableScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

		gridCustomer.add(customerTableScroll, BorderLayout.CENTER);

		customerTable.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					int idCustomer = 0;
					try {
						idCustomer = (Integer) target.getModel().getValueAt(
								row, 0);
						customerFrame(idCustomer);
					} catch (Exception ex) {
					}
				}
			}

		});

		return gridCustomer;
	}

	private JPanel makeAddCustomerPanel() {
		JPanel addPanel = new JPanel();
		GridLayout grid = new GridLayout(0, 2);
		grid.setVgap(4);

		addPanel.setLayout(grid);

		String[] addCustomerFields = { "Name", "Address", "Postal Code","Phone No.", "Email", "Type", "CVR number" };
		final JTextField[] addCustomerTextFields = new JTextField[8];

		for (int i = 0; i < addCustomerFields.length; i++) {
			JLabel fieldL = new JLabel(addCustomerFields[i]);
			addCustomerTextFields[i] = new JTextField(15);

			addPanel.add(fieldL);
			addPanel.add(addCustomerTextFields[i]);
		}


		JPanel addCustomerMain = new JPanel();
		addCustomerMain.setLayout(new BoxLayout(addCustomerMain,
				BoxLayout.Y_AXIS));
		int sp = 8;
		addCustomerMain.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black),
						"Add Customer"), BorderFactory.createEmptyBorder(sp,
						sp, sp, sp)));

		addCustomerMain.add(addPanel);

		JButton addCustButton = new JButton("Add Customer");
		addCustButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				int error = 1;

				String name = addCustomerTextFields[0].getText();
				String address = addCustomerTextFields[1].getText();
				String postalCode = addCustomerTextFields[2].getText();
				String phone = addCustomerTextFields[3].getText();
				String email = addCustomerTextFields[4].getText();
				String type = addCustomerTextFields[5].getText();
				String cvr = addCustomerTextFields[6].getText();
				
				if (name.isEmpty())
					popupError("The Name field is empty");
				else if (address.isEmpty())
					popupError("The Address field is empty");
				else if (postalCode.isEmpty())
					popupError("The Postal Code field is empty");
				else if (phone.isEmpty())
					popupError("The Phone no. field is empty");
				else if (email.isEmpty())
					popupError("The Email  field is empty");
				else if (type.isEmpty())
					popupError("The Type field is empty");
				else if (cvr.isEmpty())
					popupError("The CVR field is empty");
				else error = 0;
				
				if (error==0) {
					customerCtr.createCustomer(idC, name, address, postalCode,phone, email, cvr, type);
					idC++;
					for(int i=0;i<=6;i++)
						addCustomerTextFields[i].setText("");
					reAddGrid();
				}
			}

		});

		addPanel.add(new JLabel());
		addPanel.add(addCustButton);

		return addCustomerMain;
	}

	private void customerFrame(int idC) {

		final JFrame frame = new JFrame("Customer Id: " + idC);
		JPanel mainPanel = new JPanel();

		try {
			final Customer customer = customerCtr.getCustomer(idC);

			JLabel labID = new JLabel("Id");
			JLabel labName = new JLabel("Name");
			JLabel labAddress = new JLabel("Address");
			JLabel labPostalCode = new JLabel("Postal Code");
			JLabel labPhone = new JLabel("Phone Number");
			JLabel labEmail = new JLabel("Email");
			JLabel labType = new JLabel("Type");
			JLabel labCVR = new JLabel("CVR");

			int cols = 7;

			final JTextField textID = new JTextField(cols);
			final JTextField textName = new JTextField(cols);
			final JTextField textAddress = new JTextField(cols);
			final JTextField textPostalCode = new JTextField(cols);
			final JTextField textPhone = new JTextField(cols);
			final JTextField textEmail = new JTextField(cols);
			final JTextField textType = new JTextField(cols);
			final JTextField textCVR = new JTextField(cols);

			textID.setText(String.valueOf(customer.getId()));
			textName.setText(customer.getName());
			textAddress.setText(customer.getAddress());
			textPostalCode.setText(customer.getPostCode());
			textPhone.setText(customer.getPhone());
			textEmail.setText(customer.getEmail());
			textType.setText(customer.getType());
			textCVR.setText(customer.getCvr());

			JPanel grid1 = new JPanel();
			JPanel grid2 = new JPanel();
			JPanel grid3 = new JPanel();

			GridLayout gridLay = new GridLayout(0, 2);
			GridLayout gridLay3 = new GridLayout(0, 2);

			gridLay3.setHgap(20);

			grid1.setLayout(gridLay);
			grid2.setLayout(gridLay);
			grid3.setLayout(gridLay3);

			grid1.add(labID);
			grid1.add(textID);

			grid1.add(labName);
			grid1.add(textName);

			grid1.add(labAddress);
			grid1.add(textAddress);

			grid1.add(labPostalCode);
			grid1.add(textPostalCode);

			grid2.add(labPhone);
			grid2.add(textPhone);

			grid2.add(labEmail);
			grid2.add(textEmail);

			grid2.add(labType);
			grid2.add(textType);

			grid2.add(labCVR);
			grid2.add(textCVR);

			grid3.add(grid1);
			grid3.add(grid2);

			JPanel buttonPanel = new JPanel();
			JButton addButton = new JButton("Save");
			JButton cancelButton = new JButton("Cancel");

			buttonPanel.add(addButton);
			buttonPanel.add(cancelButton);

			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent ev) {
					frame.setVisible(false);

				}
			});

			addButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					String name = textName.getText();
					String address = textAddress.getText();
					String postalCode = textPostalCode.getText();
					String phone = textPhone.getText();
					String email = textEmail.getText();
					String type = textType.getText();
					String CVR = textCVR.getText();

					// try {}
					// catch (ParseException pe) {}

					if (name.isEmpty())
						popupError("Name field is empty");
					else if (address.isEmpty())
						popupError("Address field is empty");
					else if (postalCode.isEmpty())
						popupError("Postal Code field is empty");
					else if (phone.isEmpty())
						popupError("Phone number field is empty");
					else if (email.isEmpty())
						popupError("Email field is empty");
					else if (type.isEmpty())
						popupError("Type field is empty");
					else if (CVR.isEmpty())
						popupError("CVR field is empty");
					else {
						int answer = JOptionPane.showConfirmDialog(frame,
								"Do you wish to save? ", "Confirm saving",
								JOptionPane.YES_NO_OPTION);

						if (answer == JOptionPane.YES_OPTION) {
							customer.setName(name);
							customer.setAddress(address);
							customer.setPostCode(postalCode);
							customer.setPhone(phone);
							customer.setEmail(email);
							customer.setType(type);
							customer.setCvr(CVR);

							frame.setVisible(false);
							reAddGrid();

						}
					}
				}
			});
			mainPanel.add(grid3);
			mainPanel.add(buttonPanel);

		} catch (Exception e) {

		}

		frame.setContentPane(mainPanel);
		frame.setSize(new Dimension(400, 300));
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}

	private void reAddGrid() {
		try{
			panel.remove(1);
			panel.add(makeGridListCustomers());
			panel.revalidate();
		}catch(Exception ex){}
	}

	private void popupError(String message) {
		JOptionPane.showMessageDialog(null, message, "Error",
				JOptionPane.INFORMATION_MESSAGE);
	}

	private JPanel makeSearchPanel() {
		JPanel panel = new JPanel();
		int sp = 8;
		panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Search"),BorderFactory.createEmptyBorder(sp, sp, sp, sp)));
		
		
		JLabel labSearch = new JLabel("ID or Name ");
		final JTextField textSearch = new JTextField(10);
		JButton searchButton = new JButton("Search");

		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ev) {
				
				try {
					String search = textSearch.getText();
					
					int rowHigh = -1;
					for (int i = 0; i < size; i++)
						if (data[i][0].toString().equals(search) || (data[i][1]).toString().equals(search)) {
							rowHigh = i;
							break;
						}
					
					if (rowHigh >= 0) {
						customerTable.setRowSelectionInterval(rowHigh, rowHigh);
						customerTable.scrollRectToVisible(customerTable.getCellRect(rowHigh, 0, true));
					}
				} catch (Exception ex) {
				}
			}

		});
		
		panel.add(labSearch);
		panel.add(textSearch);
		panel.add(searchButton);

		return panel;
	}

	public JPanel makeCustomerTab() {
		panel = new JPanel();
		JPanel fourthPanel = new JPanel();
		fourthPanel.add(makeSearchPanel());
		fourthPanel.add(makeAddCustomerPanel());
		

		panel.add(fourthPanel);
		panel.add(makeGridListCustomers());

		return panel;
	}

	private int getSelectedCustomer(JTable table) {
		int count = 0;
		for (int i = 0; i < table.getRowCount(); i++) {
			if ((Boolean) table.getValueAt(i, 8) == true)
				count++;
		}
		return count;
	}

	private void deleteSelectedCustomer(JTable table) {
		for (int i = 0; i < table.getRowCount(); i++) {
			if ((Boolean) table.getValueAt(i, 8) == true) {
				int customerId = (Integer) table.getValueAt(i, 0);
				customerCtr.deleteCustomer(customerId);
			}
		}
		reAddGrid();
	}

}